import cv2
import numpy as np
if __name__ == '__main__':
    # 1. 图片输入
    image_np = cv2.imread("C:\\Users\\20436\Desktop\\xiaoxin.jpg")
    hsv_image_np = cv2.cvtColor(image_np, cv2.COLOR_BGR2HSV)
    # 2. 灰度化
    image_np_gray = cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY)

    # 3. 二值化
    _, image_np_thresh = cv2.threshold(
        image_np_gray,
        110,
        255,
        cv2.THRESH_BINARY
    )
    # 4.高斯滤波
    no_noise_image = cv2.GaussianBlur(
        image_np_thresh,  # 要滤波的图像
        (3, 3),  # 核
        1  # SigmaX
    )
    # 5. 查找轮廓
    contours, hierarchy = cv2.findContours(
        no_noise_image,
        cv2.RETR_CCOMP,
        cv2.CHAIN_APPROX_SIMPLE
    )
    print(len(contours))
    contour_image = image_np.copy()
    # 遍历轮廓
    for cnt in contours:
        # 计算最小外接矩形
        rect,a,b = cv2.minAreaRect(cnt)
        if rect[0]>400 and rect[0]<800 and  rect[1]>650 and rect[1]<704:
        # 直接绘制轮廓比绘制矩形还简单
            points = cv2.boxPoints((rect,a,b))
            points = np.int32(points)
            cv2.drawContours(
                contour_image,
                [points],
                -1,
                (0, 255, 255),
                2
            )
    cv2.imwrite('contour_image.jpg', contour_image)
    cv2.waitKey(0)